package com.zzh.utils;

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.math.BigDecimal;

/**
 * @ClassName RabbitSendMessage
 * @date 2021/4/25 16:30
 * @Version 1.0
 * @Description //rabbitmq发送消息的工具类
 * @USER root
 */
@Service
public class RabbitSendMessageUtils {

    @Autowired
    RabbitAdmin rabbitAdmin;
    public static RabbitAdmin staticRabbitAdmin;

    @PostConstruct
    private void init() {
        staticRabbitAdmin = rabbitAdmin;
    }
    /**
     * @Author zhangzhanheng
     * @Description //发送消息
     * @Date 15:18 2020/12/17
     * @Param [myqueue, sendStr]
     * @return void
     **/
    public Boolean sendMessage(String queueName, String message) {
        Boolean status = false;
        try {
            declareBinding(queueName, queueName);
            staticRabbitAdmin.getRabbitTemplate().convertAndSend(queueName, queueName, message);
            status = true;
        }catch (Exception e) {
            status  = false;
        }
        return status;
    }
    /**
     * @Author zhangzhanheng
     * @Description //绑定消息
     * @Date 15:19 2020/12/17
     * @Param [queueName, queueName1]
     * @return void
     **/
    private static void declareBinding(String exchangeName, String queueName) {
        if (staticRabbitAdmin.getQueueProperties(queueName) == null) {
            /*  queue 队列声明
            durable=true,交换机持久化,rabbitmq服务重启交换机依然存在,保证不丢失; durable=false,相反
            auto-delete=true:无消费者时，队列自动删除; auto-delete=false：无消费者时，队列不会自动删除
            排他性，exclusive=true:首次申明的connection连接下可见; exclusive=false：所有connection连接下*/
            Queue queue = new Queue(queueName, true, false, false, null);
            staticRabbitAdmin.declareQueue(queue);
            TopicExchange directExchange = new TopicExchange(exchangeName);
            staticRabbitAdmin.declareExchange(directExchange);//声明exchange
            Binding binding = BindingBuilder.bind(queue).to(directExchange).with(queueName);    //将queue绑定到exchange
            staticRabbitAdmin.declareBinding(binding);      //声明绑定关系
        } else {
            staticRabbitAdmin.getRabbitTemplate().setDefaultReceiveQueue(queueName);
            staticRabbitAdmin.getRabbitTemplate().setExchange(queueName);
            staticRabbitAdmin.getRabbitTemplate().setRoutingKey(queueName);
        }

    }
}
